package nevo.pkgs.neuro.bio;

import java.util.*;

/**
 * A class that, given a list if Spike objects, computes
 * various statistics based on the features of those spikes.
 * 
 * @author mschachter
 */
public class SpikeTrainStatistics
{
	public List<Spike> spikes;
	
	/**
	 * Vector of inter-spike intervals. The first ISI is
	 * the time-to-first spike.
	 */
	public Double[] isi;
	
	/**
	 * The average absolute peak spike height.
	 */
	public Double peakavg;
	/**
	 * The deviation of the average absolute peak spike height.
	 */
	public Double peakdev;
	
	/**
	 * The average absolute after-hyperpolarization.
	 */
	public Double ahpavg;
	/**
	 * The deviation of the average absolute after-hyperpolarization.
	 */
	public Double ahpdev;
	
	/**
	 * The average absolute voltage threshold for spiking.
	 */
	public Double threshavg;
	/**
	 * The deviation of the average absolute voltage threshold for spiking.
	 */
	public Double threshdev;
	
	
	
	public SpikeTrainStatistics(List<Spike> s)
	{
		spikes = s;
		
		computeISI();
		computeFeatures();
	}
	
	protected void computeISI()
	{	
		if (spikes.size() > 0) {
			double[] isi = new double[spikes.size()];
			isi[0] = spikes.get(0).time;
			for (int k = 1; k < spikes.size(); k++) {
				isi[k] = spikes.get(k).time - spikes.get(k-1).time;
			}
		}	
	}
	
	protected void computeFeatures()
	{
		int k;
		double peaksum = 0, ahpsum = 0, threshsum = 0;
		
		//compute averages
		for (k = 0; k < spikes.size(); k++) {
			peaksum += spikes.get(k).peak;
			ahpsum += spikes.get(k).ahp;
			threshsum += spikes.get(k).thresh;
		}
		peakavg = peaksum / spikes.size();
		ahpavg = ahpsum / spikes.size();
		threshavg = threshsum / spikes.size();
		
		peaksum = ahpsum = threshsum = 0;
		
		//compute deviations
		for (k = 0; k < spikes.size(); k++) {
			peaksum += Math.pow(spikes.get(k).peak - peakavg, 2);
			ahpsum += Math.pow(spikes.get(k).ahp - ahpavg, 2);
			threshsum += Math.pow(spikes.get(k).thresh - threshavg, 2);
		}
		peakdev = Math.sqrt(peaksum / (spikes.size()-1));
		ahpdev = Math.sqrt(ahpsum / (spikes.size()-1));
		threshdev = Math.sqrt(threshsum / (spikes.size()-1));		
	}
}
